import React, { useState, useEffect } from 'react';
import { Button, Card, Space, Input, Select, message, Switch } from 'antd';
import { AudioOutlined, PlayCircleOutlined, StopOutlined } from '@ant-design/icons';

const { TextArea } = Input;
const { Option } = Select;

interface VoiceTestProps {
  onRecognizeResult?: (text: string, type: 'wakeup' | 'recognize') => void;
}

const VoiceTest: React.FC<VoiceTestProps> = ({ onRecognizeResult }) => {
  const [isRecording, setIsRecording] = useState(false);
  const [testText, setTestText] = useState('你好，这是一个测试语音识别功能');
  const [recognizeType, setRecognizeType] = useState<'wakeup' | 'recognize'>('recognize');
  const [isChatLabAvailable, setIsChatLabAvailable] = useState(false);
  const [isOnRecognizeWordsAvailable, setIsOnRecognizeWordsAvailable] = useState(false);
  const [recognizedResults, setRecognizedResults] = useState<Array<{text: string, type: string, timestamp: number}>>([]);

  // 检查 ChatLab 是否可用
  useEffect(() => {
    const checkChatLab = () => {
      const hasChatLab = !!(window as any).ChatLab;
      const hasOnRecognizeWords = !!(window as any).onRecognizeWords;
      
      setIsChatLabAvailable(hasChatLab);
      setIsOnRecognizeWordsAvailable(hasOnRecognizeWords);
      
      console.log('🔍 ChatLab 检查结果:', {
        hasChatLab,
        hasOnRecognizeWords,
        ChatLabMethods: hasChatLab ? Object.keys((window as any).ChatLab) : [],
      });
    };

    checkChatLab();
    
    // 监听 window 对象变化
    const observer = new MutationObserver(checkChatLab);
    observer.observe(document, { childList: true, subtree: true });
    
    return () => observer.disconnect();
  }, []);

  // 模拟 ChatLab 方法
  const mockChatLab = () => {
    if (!(window as any).ChatLab) {
      (window as any).ChatLab = {
        wakeup: () => {
          console.log('🎤 模拟 ChatLab.wakeup() 被调用');
          message.success('语音唤醒功能已开启');
        },
        startRecognize: () => {
          console.log('🎤 模拟 ChatLab.startRecognize() 被调用');
          message.success('开始语音识别');
          setIsRecording(true);
        },
        stopRecognize: () => {
          console.log('🎤 模拟 ChatLab.stopRecognize() 被调用');
          message.success('停止语音识别');
          setIsRecording(false);
        }
      };
      setIsChatLabAvailable(true);
      message.success('ChatLab 模拟对象已创建');
    }
  };

  // 模拟语音识别结果
  const simulateVoiceRecognition = () => {
    if (!(window as any).onRecognizeWords) {
      message.error('onRecognizeWords 回调未设置');
      return;
    }

    const result = {
      words: testText,
      type: recognizeType
    };

    console.log('🎯 模拟语音识别结果:', result);
    
    // 调用 onRecognizeWords 回调
    (window as any).onRecognizeWords(result);
    
    // 记录结果
    setRecognizedResults(prev => [...prev, {
      text: testText,
      type: recognizeType,
      timestamp: Date.now()
    }]);

    // 如果设置了外部回调，也调用它
    if (onRecognizeResult) {
      onRecognizeResult(testText, recognizeType);
    }
  };

  // 模拟流式语音识别（逐字显示）
  const simulateStreamingRecognition = () => {
    if (!(window as any).onRecognizeWords) {
      message.error('onRecognizeWords 回调未设置');
      return;
    }

    setIsRecording(true);
    let currentText = '';
    const words = testText.split('');
    let index = 0;

    const interval = setInterval(() => {
      if (index < words.length) {
        currentText += words[index];
        
        const result = {
          words: currentText,
          type: recognizeType
        };

        console.log('🎯 流式识别结果:', result);
        (window as any).onRecognizeWords(result);
        
        // 记录最终结果
        if (index === words.length - 1) {
          setRecognizedResults(prev => [...prev, {
            text: currentText,
            type: recognizeType,
            timestamp: Date.now()
          }]);
          
          if (onRecognizeResult) {
            onRecognizeResult(currentText, recognizeType);
          }
        }
        
        index++;
      } else {
        clearInterval(interval);
        setIsRecording(false);
      }
    }, 200); // 每200ms显示一个字
  };

  // 测试 ChatLab 方法调用
  const testChatLabMethods = () => {
    if (!(window as any).ChatLab) {
      message.error('ChatLab 不可用，请先创建模拟对象');
      return;
    }

    try {
      console.log('🧪 开始测试 ChatLab 方法...');
      
      // 测试 wakeup
      (window as any).ChatLab.wakeup();
      
      // 测试 startRecognize
      setTimeout(() => {
        (window as any).ChatLab.startRecognize();
      }, 1000);
      
      // 测试 stopRecognize
      setTimeout(() => {
        (window as any).ChatLab.stopRecognize();
      }, 3000);
      
      message.success('ChatLab 方法测试完成，请查看控制台');
    } catch (error) {
      console.error('ChatLab 方法测试失败:', error);
      message.error('ChatLab 方法测试失败');
    }
  };

  // 清除识别结果
  const clearResults = () => {
    setRecognizedResults([]);
  };

  return (
    <div className="p-4 max-w-4xl mx-auto">
      <Card title="🎤 语音识别功能测试" className="mb-4">
        <Space direction="vertical" size="large" className="w-full">
          
          {/* 状态检查 */}
          <Card size="small" title="📊 功能状态检查">
            <Space direction="vertical">
              <div className="flex items-center gap-2">
                <span>ChatLab 可用:</span>
                <Switch 
                  checked={isChatLabAvailable} 
                  disabled 
                  checkedChildren="✅" 
                  unCheckedChildren="❌" 
                />
              </div>
              <div className="flex items-center gap-2">
                <span>onRecognizeWords 可用:</span>
                <Switch 
                  checked={isOnRecognizeWordsAvailable} 
                  disabled 
                  checkedChildren="✅" 
                  unCheckedChildren="❌" 
                />
              </div>
            </Space>
          </Card>

          {/* ChatLab 模拟 */}
          <Card size="small" title="🔧 ChatLab 模拟设置">
            <Space direction="vertical" className="w-full">
              <Button 
                type="primary" 
                onClick={mockChatLab}
                disabled={isChatLabAvailable}
              >
                创建 ChatLab 模拟对象
              </Button>
              <Button 
                onClick={testChatLabMethods}
                disabled={!isChatLabAvailable}
              >
                测试 ChatLab 方法调用
              </Button>
            </Space>
          </Card>

          {/* 语音识别测试 */}
          <Card size="small" title="🎯 语音识别测试">
            <Space direction="vertical" className="w-full">
              <div>
                <label className="block mb-2">识别类型:</label>
                <Select 
                  value={recognizeType} 
                  onChange={setRecognizeType}
                  style={{ width: 200 }}
                >
                  <Option value="wakeup">唤醒 (wakeup)</Option>
                  <Option value="recognize">识别 (recognize)</Option>
                </Select>
              </div>
              
              <div>
                <label className="block mb-2">测试文本:</label>
                <TextArea
                  value={testText}
                  onChange={(e) => setTestText(e.target.value)}
                  rows={3}
                  placeholder="输入要模拟识别的文本"
                />
              </div>
              
              <Space>
                <Button 
                  type="primary" 
                  icon={<AudioOutlined />}
                  onClick={simulateVoiceRecognition}
                  disabled={!isOnRecognizeWordsAvailable}
                >
                  模拟单次识别
                </Button>
                <Button 
                  type="primary" 
                  icon={<PlayCircleOutlined />}
                  onClick={simulateStreamingRecognition}
                  disabled={!isOnRecognizeWordsAvailable || isRecording}
                  loading={isRecording}
                >
                  模拟流式识别
                </Button>
                <Button 
                  icon={<StopOutlined />}
                  onClick={() => setIsRecording(false)}
                  disabled={!isRecording}
                >
                  停止识别
                </Button>
              </Space>
            </Space>
          </Card>

          {/* 识别结果 */}
          <Card size="small" title="📝 识别结果记录">
            <Space direction="vertical" className="w-full">
              <div className="flex justify-between items-center">
                <span>共 {recognizedResults.length} 条记录</span>
                <Button size="small" onClick={clearResults}>
                  清除记录
                </Button>
              </div>
              
              <div className="max-h-60 overflow-y-auto">
                {recognizedResults.length === 0 ? (
                  <div className="text-gray-500 text-center py-4">
                    暂无识别结果
                  </div>
                ) : (
                  recognizedResults.map((result, index) => (
                    <div 
                      key={index} 
                      className="border-b border-gray-200 py-2"
                    >
                      <div className="flex justify-between items-start">
                        <div className="flex-1">
                          <div className="font-medium">{result.text}</div>
                          <div className="text-sm text-gray-500">
                            类型: {result.type} | 
                            时间: {new Date(result.timestamp).toLocaleTimeString()}
                          </div>
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </div>
            </Space>
          </Card>

          {/* 使用说明 */}
          <Card size="small" title="📖 使用说明">
            <div className="text-sm text-gray-600 space-y-2">
              <p>1. 首先点击"创建 ChatLab 模拟对象"来模拟原生 App 的 ChatLab 功能</p>
              <p>2. 可以测试 ChatLab 的方法调用是否正常工作</p>
              <p>3. 设置识别类型和测试文本，然后模拟语音识别</p>
              <p>4. 支持单次识别和流式识别两种模式</p>
              <p>5. 所有识别结果都会记录在下方，方便查看测试效果</p>
              <p>6. 在浏览器控制台可以看到详细的调用日志</p>
            </div>
          </Card>
        </Space>
      </Card>
    </div>
  );
};

export default VoiceTest; 